from pymongo import MongoClient
import json
import _redis
import base64
with open('../config.py', 'r') as f:
    exec(f.read())


fp_ip = yituinfo['ip']
fp_port = yituinfo['port']

conn_ = MongoClient(mongoinfo['ip'], mongoinfo['port'])

face90_ = conn_.guidang4.face90
acvs_ = conn_.guidang4.acvs
capture_ = conn_.guidang4.capture
cardacvs_ = conn_.guidang4.cardacvs  # 获取档案id对应的证件 或者 证件照 对应的档案id
cardface_ = conn_.guidang4.cardface
acvsacvs_ = conn_.guidang4.acvsacvs
faceacvs_ = conn_.guidang4.faceacvs
card_ = conn_.guidang4.card
acvstree_ = conn_.guidang4.acvstree
ovodata_ = conn_.guidang4.ovodata


# ovoImg
def get_ovo_img():
    img_list = []
    allimg = ovodata_.find({'ovo': {'$lte': 0.4, '$gt': 0}}).limit(200)
    for img in allimg:
        dic1 = {'url': img['a_url'], 'ovo': img['ovo'], 'ovn': img['ovn'], 'yituovo': img['yituovo']}
        dic2 = {'url': img['b_url'], 'ovo': img['ovo'], 'ovn': img['ovn'], 'yituovo': img['yituovo']}
        img_list.append(dic1)
        img_list.append(dic2)

    return img_list


def one_count(img_p, con_count, already_query_list, all_img_list):
    two_acvs_list = []
    if len(img_p['correlation']) > 0:
        for key in img_p['correlation'][0]:
            if img_p['correlation'][0][key] >= con_count:
                two_acvs_list.append(key)
                key_img = acvstree_.find_one({'_id': key})
                key_img['face_image_uri'] = get_url(key_img['face_image_uri'])

                all_img_list.append(key_img)
        already_query_list.append(img_p['_id'])
        return two_acvs_list
    return []

def two_count(two_acvs_list, con_count, already_query_list, all_img_list):
    three_acvs_list = []
    for acvs_id in two_acvs_list:
        acvs_img = acvstree_.find_one({'_id': acvs_id})
        acvs_img['face_image_uri'] = get_url(acvs_img['face_image_uri'])
        if acvs_img not in all_img_list:
            all_img_list.append(acvs_img)
        for key in acvs_img['correlation'][0]:
            if acvs_img['correlation'][0][key] >= con_count and acvs_img['correlation'][0][key] not in already_query_list:
                three_acvs_list.append(key)
                key_img = acvstree_.find_one({'_id': key})
                key_img['face_image_uri'] = get_url(key_img['face_image_uri'])
                if key_img not in all_img_list:

                    all_img_list.append(key_img)
        already_query_list.append(acvs_id)
    return three_acvs_list



# acvstree  任意档案获取所有档案列表 外加次数限制
def count_limit(img_p, count, con_count, all_img_list):
    # 已查询列表
    already_query_list = []

    # 第一次查询必须查
    two_acvs_list = one_count(img_p, con_count, already_query_list, all_img_list)
    count_dic = {}
    count_dic[2] = two_acvs_list
    for i in range(1, count):
        if len(count_dic[i + 1]) == 0:
            break
        if len(count_dic[i + 1]) > 0:
            count_dic[i + 2] = two_count(count_dic[i + 1],  con_count, already_query_list, all_img_list)

    # if len(two_acvs_list) > 0 and count > 1:
    #     three_acvs_list = two_count(two_acvs_list, con_count, already_query_list, all_img_list)
    #     if len(three_acvs_list) and count > 2:
    #         four_acvs_list = two_count(three_acvs_list, con_count, already_query_list, all_img_list)

def one_get_all_acvs(acvs_id, **kwargs):
    # 修改事项- 添加两个限制 查询次数限制和亲密度限制
    if 'count' in kwargs:
        count = kwargs['count']
    else:
        count = 3
    if 'con_count' in kwargs:
        con_count = kwargs['con_count']
    else:
        con_count = 1

    img = acvstree_.find_one({'_id': acvs_id})
    all_img_list = []

    if img['p'] is None:
        img['face_image_uri'] = get_url(img['face_image_uri'])
        img_p = img
        all_img_list.append(img_p)

    else:
        img_p = acvstree_.find_one({'_id': img['p']})
        img_p['face_image_uri'] = get_url(img_p['face_image_uri'])
        all_img_list.append(img_p)

    count_limit(img_p, count, con_count, all_img_list)
    all_img_list = sorted(all_img_list, key=lambda x: x['count'], reverse=True)

    return all_img_list
# 显示第一页的信息
def get_p_list():
    allimg = acvstree_.find({'p': None})
    p_list = []
    for p_img in allimg:
        p_img['face_image_uri'] = get_url(p_img['face_image_uri'])
        p_list.append(p_img)

    p_list = sorted(p_list, key=lambda x: x['count'], reverse=True)
    return p_list


# 所有档案id--acvs_获取-长度-更新时间         遍历face90_可以获取档案长度
# 列表中存元组 - 档案id 及其里面的数量
# 档内所有的face_id--capture_获取            获取face90_ id 获取 face_id
# 存放字典



def get_url(uri):
    # return uri
    arr = uri.split('@')
    uri = arr[0] + '@' + arr[1]
    cluster_id = arr[2]
    return 'http://' + fp_ip + ':' + str(fp_port) + '/storage/v1/image/global?cluster_id=' + cluster_id + '&uri_base64=' + tobase64(uri)

def tobase64(str):
    encodestr = base64.b64encode(str.encode('utf-8'))
    return encodestr.decode()

# def get_url(faceurl):
#     cluster_id = 'YD_1576089340'
#     faceurl = faceurl[:-len(cluster_id)-1]
#     faceurl_base64 = base64.b64encode(faceurl.encode())
#     return 'http://192.168.1.88:11180/storage/v1/image/global?cluster_id=YD_1576089340&uri_base64=' + faceurl_base64.decode()

def cardList(acvs_id):
    imgall = cardacvs_.find({'acvs_id': acvs_id})
    card_list = []
    for img in imgall:
        img['face_image_uri'] = get_url(img['face_image_uri'])
        card_list.append(img)

    return card_list



def cardacvsshow(acvs_id, card_id):
    imgacvs = acvs_.find_one({'_id': acvs_id})
    img = {}
    img1 = cardacvs_.find_one({'acvs_id': acvs_id, 'card_id': card_id})
    img['similarity_high'] = img1['similarity_high']
    img['similarity_low'] = img1['similarity_low']
    img['similarity_average'] = img1['similarity_average']
    img['count'] = img1['count']
    img['level'] = img1['level']
    img['acvs_id'] = acvs_id
    img['face_id'] = imgacvs['f_id']
    img['face_image_uri'] = get_url(imgacvs['face_image_uri'])
    return img


#
def acvsshow(acvs_id, acvsfollow):
    imgacvs = acvs_.find_one({'_id': acvsfollow})
    p_id = imgacvs['f_id']
    img = acvsacvs_.find_one({'acvssrc': acvs_id, 'acvsfllow': acvsfollow})
    img['face_id'] = p_id
    img['face_image_uri'] = get_url(imgacvs['face_image_uri'])
    return img


def acvsacvs(acvs_id):
    imgall = acvsacvs_.find({'acvssrc': acvs_id})
    acvs_list = []
    for acvsimg in imgall:
        acvs_list.append(acvsimg['acvsfllow'])

    # acvs_list = sorted(acvs_list, key=lambda x: x['score'])
    return acvs_list


# 1.档案内脸的数量， 按由大到小排序 2. 档案内一级脸的数量
def getfaceacvs(acvs_id):
    imgall = faceacvs_.find({'acvs_id': acvs_id})
    face_list = []
    for img in imgall:
        img['face_image_uri'] = get_url(img['face_image_uri'])
        face_list.append(img)

    face_list = sorted(face_list, key=lambda x: x['score'])
    return face_list



def gatallfaceid(cardid):
    # 获取证对应的脸
    imgall = cardface_.find({'card_id': cardid})
    face_list = []
    for img in imgall:
        img['face_image_uri'] = get_url(img['face_face_image_uri'])
        face_list.append(img)

    face_list = sorted(face_list, key=lambda x: x['similarity'], reverse=True)
    return face_list


def getallacvsid(cardid):
    # 获取证对应的档
    imgall = cardacvs_.find({'card_id': cardid})
    acvs_list = []
    for img in imgall:
        acvs_list.append((img['acvs_id'], img['similarity_high']))
    acvs_list = sorted(acvs_list, key=lambda x: x[1])

    return acvs_list


def getcardimgg(cardid):
    img = card_.find_one({'_id': cardid})
    img['face_image_uri'] = get_url(img['face_image_uri'])
    return img


def getcardlist():
    # 统计所有证的列表
    imgall = card_.find({})

    card_list = []
    for img in imgall:
        img['face_image_uri'] = get_url(img['face_image_uri'])
        card_list.append(img)

    card_list = sorted(card_list, key=lambda x: x['lenface'], reverse=True)

    return card_list




def getcardf(card_id, plist):
    # card_face list
    card_face_list = []
    card_face_img = cardface_.find({'card_id': card_id})
    for img in card_face_img:
        for face_img in plist:
            if img['face_id'] == face_img[0]:
                card_face_list.append((img['face_id'], img['score'], face_img[3]))
    # 降序排列
    card_face_lis = sorted(card_face_list, key=lambda x: x[1], reverse=True)
    return card_face_lis


# 通过档案id 获取命中的证件id -- 并得到命中证件id的face_id排序
def getcarda(acvs_id):
    allimg = cardacvs_.find({'acvs_id': acvs_id})
    # 命中证件列表
    card_sim_list = []
    for img in allimg:
        card_sim_list.append((img['card_id'], img['similarity'], img['f_url']))
    # 按相似度排序card 降序
    card_sim_lis = sorted(card_sim_list, key=lambda x: x[2], reverse=True)
    return card_sim_lis


def getcardimg(acvs_id, card_id):
    card_img = cardacvs_.find_one({'acvs_id': acvs_id, 'card_id': card_id})
    del card_img['_id']
    return card_img


# 档案id中的 所有脸的id
# db15的所有信息--capture_获取
def get_outall_img(face_id):
    face_img = face90_.find_one({'face_id': face_id})
    del face_img['_id']

    return face_img


def get_outall_imgcard(face_id, card_id):
    face_img = face90_.find_one({'face_id': face_id})
    img = cardface_.find_one({'card_id': card_id, 'face_id': face_id})
    del face_img['_id']
    face_img['similarity'] = img['score']
    return face_img


def get_outacvs_id():
    outscvs_id_map = {}
    for item in face90_.find():
        acvs_id = item['acvs_idd']
        if acvs_id not in outscvs_id_map:
            outscvs_id_map[acvs_id] = 0
        outscvs_id_map[acvs_id] += 1
    # 字典从大到小排序  列表里面的元组
    outscvs_id_list = sorted(outscvs_id_map.items(), key=lambda d: d[1], reverse=True)
    return outscvs_id_list


def get_outface_id(acvs_id):
    # 先不排序
    face_id_list = []
    for item in face90_.find({'acvs_idd': acvs_id}):
        face_id_list.append((item['face_id'], item['f_url']))
    return face_id_list


def get_acvs_id():
    acv_id_list = []
    for item in acvs_.find():
        acv_id_list.append((item['_id'], item['len1'], item['len2'], item['len3'], item['acvslen1'], item['acvslen2'],
                            item['acvslen3'], get_url(item['face_image_uri']), item['f_id'], item['lencard']))

    acv_id_list = sorted(acv_id_list, key=lambda x: x[1], reverse=True)

    return acv_id_list



def get_all_img(face_id):
    face_img = capture_.find_one({"_id": face_id})
    return face_img


def get_all_imgcard(face_id, card_id):
    face_img = capture_.find_one({'_id': face_id})
    img = cardface_.find_one({"card_id": card_id, "face_id": face_id})
    face_img['similarity'] = img['similarity']
    face_img['face_image_uri'] = get_url(face_img['face_image_uri'])
    return face_img


# 圈内和圈外混合  返回固定档案id的 所有 face_id 和 face_url,  加字段 0外 1内
def get_all_face_id(acvs_id):
    face_id_list = []
    face_iid_list = []
    for item in capture_.find({'acvs_id': acvs_id}):
        face_iid_list.append(item['_id'])
        face_id_list.append((item['_id'], item['f_url'], item['timestamp'], 1))
    faceout_id_list = []
    faceout_iid_list = []
    for itemout in face90_.find({'acvs_idd': acvs_id}):
        faceout_iid_list.append(itemout['face_id'])
        faceout_id_list.append((itemout['face_id'], itemout['f_url'], itemout['timestamp'], 0))

    for iid in face_iid_list:
        if iid in faceout_iid_list:
            img = face90_.find_one({'face_id': iid})
            url = img['f_url']
            time = img['timestamp']
            faceout_id_list.remove((iid, url, time, 0))
    all_list = face_id_list + faceout_id_list
    # 进行排序按时间倒序
    aall_list = sorted(all_list, key=lambda x: x[2], reverse=True)
    return aall_list


# one_get_all_acvs('70d969f6-5279-11ea-b7ad-0028f80f26fd')
